{% extends "base.html" %}

{% block content %}
<div class="page-title">
    <h3>在下方添加员工信息：</h3>
</div>
<div class="form-container">
    <form id="add-employee-form">
        <label for="employee_id">员工编号：</label>
        <input type="number" id="employee_id" name="employee_id" class="input-field" required><br>
        <label for="employee_name">员工姓名：</label>
        <input type="text" id="employee_name" name="employee_name" class="input-field" required><br>
        <label for="password">密码：</label>
        <input type="text" id="password" name="password" class="input-field" required><br>
        <label for="level">级别：</label>
        <input type="number" id="level" name="level" class="input-field"><br>
        <label for="phone">电话：</label>
        <input type="text" id="phone" name="phone" class="input-field"><br>
        <label for="salary">工资：</label>
        <input type="number" id="salary" name="salary" class="input-field"><br>
        <label for="remark">备注：</label>
        <textarea id="remark" name="remark" class="input-field"></textarea><br>
        <div class="button-container">
            <button type="submit" class="login-button">保存</button>
            <button type="reset" class="login-button" style="background-color: grey;">重置</button>
        </div>
    </form>
</div>

<script>
    document.getElementById('add-employee-form').addEventListener('submit', function(event) {
        event.preventDefault();

        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        const criticalFields = ['level', 'phone', 'salary'];
        let incomplete = false;
        for (const field of criticalFields) {
            if (!data[field]) {
                incomplete = true;
                break;
            }
        }

        if (incomplete) {
            if (!confirm('输入的信息不全，是否确定保存？')) {
                return;
            }
        }

        fetch('/api/employees', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => {
            if (response.ok) {
                alert('员工添加成功');
                this.reset();
            } else {
                response.json().then(data => {
                    alert('添加员工失败: ' + data.error);
                });
            }
        }).catch(error => {
            console.error('Error:', error);
            alert('添加员工失败');
        });
    });

    document.querySelector('button[type="reset"]').addEventListener('click', function(event) {
        if (!confirm('是否确定重置已输入信息？')) {
            event.preventDefault();
        }
    });
</script>
{% endblock %}
